/**
 * AssessmentService.java
 * Version 1.0.0
 * Created on 2018年8月27日
 */
package com.yincheng.oes.business.assessment.service;

import com.yincheng.oes.business.config.PaperResultStatus;
import com.yincheng.oes.business.consist.PaperStatusEnum;
import com.yincheng.oes.business.exam.base.entity.Paper;
import com.yincheng.oes.business.exam.base.mapper.PaperMapper;
import com.yincheng.oes.business.exam.judgepaper.entity.PaperResult;
import com.yincheng.oes.business.exam.judgepaper.entity.PaperResultQues;
import com.yincheng.oes.business.exam.judgepaper.entity.PaperStudentResult;
import com.yincheng.oes.business.exam.judgepaper.mapper.PaperResultDetailMapper;
import com.yincheng.oes.business.exam.judgepaper.mapper.PaperResultMapper;
import com.yincheng.oes.sso.util.UserUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author yangsy
 * @version 1.0.0
 * @since 创建时间：2018年8月27日
 * <p>
 * 功能描述：
 * <p>
 * 邮箱地址：446948434@qq.com
 */
@Service
public class AssessmentService {

    /**
     * 日志
     */
    private static final Logger LOGGER = LogManager.getLogger(AssessmentService.class);

    private static final String INVALID_STATUS_PAPER_NAME = "该试卷已被下架，请联系客服";

    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private PaperResultDetailMapper paperResultDetailMapper;

    @Autowired
    private PaperResultMapper paperResultMapper;

    /**
     * 获取答卷信息
     *
     * @param paperId
     * @return
     */
    public PaperStudentResult getNewPaperByPaperId(String paperId) {
        PaperStudentResult myPaper = new PaperStudentResult();
        Paper paper = paperMapper.selectById(paperId);
        if (PaperStatusEnum.INVALID.getStatus().equals(paper.getStatus())) {
            myPaper.setPaperName(INVALID_STATUS_PAPER_NAME);
            return myPaper;
        }
        myPaper.setCreateUserName(paper.getCreateUserName());
        myPaper.setId(UUID.randomUUID().toString());
        myPaper.setPaperCreateTime(paper.getCreateTime());
        myPaper.setPaperId(paperId);
        myPaper.setPaperName(paper.getPaperName());
        myPaper.setStatus(PaperResultStatus.DURING_ANSWER.getStatus());

        List<PaperResultQues> paperResultDetails = paperResultDetailMapper.selectDetailsByPaperId(paperId);
        myPaper.setPaperResultDetails(paperResultDetails);

        int i = paperResultMapper.update(myPaper);
        if (i == 0) {
            myPaper.setStartTime(new Date());
            paperResultMapper.insert(myPaper);
        }

        return myPaper;
    }

    public PaperStudentResult getNewPaperByPaperIdInternal(String paperId) {
        PaperStudentResult myPaper = new PaperStudentResult();
        Paper paper = paperMapper.selectById(paperId);
        if (PaperStatusEnum.INVALID.getStatus().equals(paper.getStatus())) {
            myPaper.setPaperName(INVALID_STATUS_PAPER_NAME);
            return myPaper;
        }
        myPaper.setCreateUserName(paper.getCreateUserName());
        myPaper.setId(UUID.randomUUID().toString());
        myPaper.setPaperCreateTime(paper.getCreateTime());
        myPaper.setPaperId(paperId);
        myPaper.setPaperName(paper.getPaperName());
        myPaper.setStatus(PaperResultStatus.DURING_ANSWER.getStatus());
        myPaper.setUserId(UserUtils.getUser().getUserId());
        myPaper.setUserName(UserUtils.getUser().getUserName());

        List<PaperResultQues> paperResultDetails = paperResultDetailMapper.selectDetailsByPaperId(paperId);
        myPaper.setPaperResultDetails(paperResultDetails);

        return myPaper;
    }

    /**
     * 获取试卷基础信息
     *
     * @param paperId
     * @return
     */
    public Paper getBasePaperByPaperId(String paperId) {
        Paper paper = paperMapper.selectById(paperId);
        if (PaperStatusEnum.INVALID.getStatus().equals(paper.getStatus())) {
            paper = new Paper();
            paper.setPaperName(INVALID_STATUS_PAPER_NAME);
        }
        return paper;
    }

    public PaperStudentResult getPaperResult(String resultId) {
        PaperStudentResult paperResult = paperResultMapper.selectByResultId(resultId);
        if (paperResult == null) {
            throw new IllegalArgumentException("此答卷尚未保存或数据异常");
        }
        Paper paper = paperMapper.selectById(paperResult.getPaperId());
        if (PaperStatusEnum.INVALID.getStatus().equals(paper.getStatus())) {
            paperResult = new PaperStudentResult();
            paperResult.setPaperName(INVALID_STATUS_PAPER_NAME);
            return paperResult;
        }

        Integer tatal = paperResultDetailMapper.countByResultId(resultId);
        List<PaperResultQues> list = null;
        if (tatal > 0) {
            list = paperResultDetailMapper.selectDetailsByResultId(resultId);
        } else {
            list = paperResultDetailMapper.selectDetailsByPaperId(paperResult.getPaperId());
        }
        Float totalScore = Float.valueOf(0);
        Float standardScore = Float.valueOf(0);
        for (PaperResultQues paperResultQues : list) {

            totalScore = totalScore + paperResultQues.getScore();
            standardScore = standardScore + paperResultQues.getStandardScore();
        }
        paperResult.setPaperResultDetails(list);
        paperResult.setScore(totalScore);
        paperResult.setStandardScore(standardScore);
        return paperResult;
    }

    @Transactional
    public PaperStudentResult getPaperResult(String paperId, String userName) {
        PaperStudentResult myPaper = paperResultMapper.selectByPaperIdAndUserName(paperId, userName);
        if (myPaper == null) {
            myPaper = new PaperStudentResult();
            Paper paper = paperMapper.selectById(paperId);
            if (PaperStatusEnum.INVALID.getStatus().equals(paper.getStatus())) {
                myPaper.setPaperName(INVALID_STATUS_PAPER_NAME);
                return myPaper;
            }
            myPaper.setCreateUserName(paper.getCreateUserName());
            myPaper.setId(UUID.randomUUID().toString());
            myPaper.setPaperCreateTime(paper.getCreateTime());
            myPaper.setPaperId(paperId);
            myPaper.setPaperName(paper.getPaperName());
            myPaper.setStatus(PaperResultStatus.DURING_ANSWER.getStatus());
            myPaper.setUserName(userName);
            myPaper.setStartTime(new Date());
            int update = paperResultMapper.update(myPaper);
            if (update == 0) {
                paperResultMapper.insert(myPaper);
            } else {
                LOGGER.info("this student {} open {} duplicate", userName, paper.getPaperName());
                return paperResultMapper.selectByPaperIdAndUserName(paperId, userName);
            }
        }
        return myPaper;
    }

    @Transactional
    public PaperStudentResult savePaperResult(PaperResult bean) {
        List<PaperResultQues> resultDetails = bean.getPaperResultDetails();

        paperResultDetailMapper.deleteByResultId(bean.getId());
        Float score = (float) 0;
        for (PaperResultQues e : resultDetails) {
            if (e.getAnswer().equals(e.getMyAnswer())) {
                e.setCorrectFlag("1");
                score = score + e.getStandardScore();
            } else {
                e.setCorrectFlag("0");
            }
            e.setPaperResultId(bean.getId());
            e.setCreateTime(new Date());
            paperResultDetailMapper.insert(e);
        }
        bean.setScore(score);
        bean.setEndTime(new Date());
        int i = paperResultMapper.update(bean);
        if (i == 0) {
            paperResultMapper.insert(bean);

        }

        PaperStudentResult paperResult = paperResultMapper.selectByResultId(bean.getId());
        Integer tatal = paperResultDetailMapper.countByResultId(bean.getId());
        List<PaperResultQues> list = null;
        if (tatal > 0) {
            list = paperResultDetailMapper.selectDetailsByResultId(bean.getId());
        } else {
            list = paperResultDetailMapper.selectDetailsByPaperId(bean.getPaperId());
        }

        Float totalScore = Float.valueOf(0);
        Float standardScore = Float.valueOf(0);
        for (PaperResultQues paperResultQues : list) {
            totalScore = totalScore + paperResultQues.getScore();
            standardScore = standardScore + paperResultQues.getStandardScore();
        }
        paperResult.setScore(totalScore);
        paperResult.setStandardScore(standardScore);
        return paperResult;
    }
}
